package com.lsongh.controller;

import com.lsongh.entity.Student;
import com.lsongh.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by Administrator on 2017/10/19.
 */
@RestController
public class StudentController {
    @Autowired
    StudentService studentService;

    /*查询所有学生*/
    @RequestMapping(value = "student", method = RequestMethod.GET)
    public List<Student> Student() {
        return studentService.findAll();
    }

    /*增加一个学生*/
    @RequestMapping(value = "student", method = RequestMethod.POST)
    public Student addStudent(@Valid Student student, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            System.out.println(bindingResult.getFieldError().getDefaultMessage());
            return null;
        }
        student.setStudentName(student.getStudentName());
        student.setStudentAddress(student.getStudentAddress());
        student.setStudentPhone(student.getStudentPhone());
        student.setStudentSex(student.getStudentSex());
        return studentService.save(student);
    }

    /*通过id查找一个学生*/
    @RequestMapping(value = "student/{stuentId}", method = RequestMethod.GET)
    public Student findStudent(@PathVariable("stuentId") Integer stuentId) {
        return studentService.findOne(stuentId);
    }

    /*通过id更新一个学生*/
    @RequestMapping(value = "student/{stuentId}", method = RequestMethod.PUT)
    public Student updateStudent(@PathVariable("stuentId") Integer stuentId,
                                 @RequestParam("studentName") String studentName,
                                 @RequestParam("studentSex") String studentSex,
                                 @RequestParam("studentPhone") String studentPhone,
                                 @RequestParam("studentAddress") String studentAddress) {
        Student student = new Student();
        student.setStuentId(stuentId);
        student.setStudentName(studentName);
        student.setStudentSex(studentSex);
        student.setStudentAddress(studentAddress);
        student.setStudentPhone(studentPhone);
        return studentService.save(student);
    }


    /*通过id删除一个学生*/
    @RequestMapping(value = "student/{stuentId}", method = RequestMethod.DELETE)
    public String deleteStudent(@PathVariable("stuentId") Integer stuentId) {
        studentService.delete(stuentId);
        return "ok ,deleted";
    }
}
